/*
 * hton64 - Byte order convert library
 * author	: calvin
 * email	: calvinwilliams@163.com
 *
 * Licensed under the LGPL v2.1, see the file LICENSE in base directory.
 */

#ifndef _H_HTOL64_
#define _H_HTOL64_

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

union __EndianTest { uint32_t mylong; unsigned char c[4]; } ;
extern union __EndianTest __endian_test ;
#define ENDIANNESS  (__endian_test.c[0])

#define _swpe16(data)	((((data) & 0xff00) >> 8) | (((data) & 0x00ff) << 8))
#define _swpe32(data)	((((data) & 0xff000000) >> 24)			  \
				| (((data) & 0x00ff0000) >> 16)		  \
				| (((data) & 0x0000ff00) << 16)		  \
				| (((data) & 0x000000ff) << 24))
#define _swpe64(data)	((((data) & (uint64_t)(0xff00000000000000)) >> 56)	   \
				| (((data) & (uint64_t)(0x00ff000000000000)) >> 40)  \
				| (((data) & (uint64_t)(0x0000ff0000000000)) >> 24)  \
				| (((data) & (uint64_t)(0x000000ff00000000)) >> 16)  \
				| (((data) & (uint64_t)(0x00000000ff000000)) << 16)  \
				| (((data) & (uint64_t)(0x0000000000ff0000)) << 24)  \
				| (((data) & (uint64_t)(0x000000000000ff00)) << 40)  \
				| (((data) & (uint64_t)(0x00000000000000ff)) << 56))

#ifndef be16toh
#define be16toh(data)	( (ENDIANNESS) ? (data) : _swpe16(data))
#define le16toh(data)	((!ENDIANNESS) ? (data) : _swpe16(data))
#define htobe16(data)	(be16toh(data))
#define htole16(data)	(le16toh(data))
#endif

#ifndef hton16
#define hton16(data)	(htobe16(data))
#define ntoh16(data)	(be16toh(data))
#endif

#ifndef be32toh
#define be32toh(data)	( (ENDIANNESS) ? (data) : _swpe32(data))
#define htobe32(data)	(be32toh(data))
#define le32toh(data)	((!ENDIANNESS) ? (data) : _swpe32(data))
#define htole32(data)	(le32toh(data))
#endif

#ifndef hton32
#define hton32(data)	(htobe32(data))
#define ntoh32(data)	(be32toh(data))
#endif

#ifndef be64toh
#define be64toh(data)	( (ENDIANNESS) ? (data) : _swpe64(data))
#define htobe64(data)	(be64toh(data))
#define le64toh(data)	((!ENDIANNESS) ? (data) : _swpe64(data))
#define htole64(data)	(le64toh(data))
#endif

#ifndef hton64
#define hton64(data)	(htobe64(data))
#define ntoh64(data)	(be64toh(data))
#endif

#ifdef __cplusplus
}
#endif

#endif

